package com.zhiyizhen.callnumber.net.progress;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Looper;


import java.lang.ref.WeakReference;

public class ProgressDialogHandlerImpl implements IProgressDialogHandler {

    private static final int DELAY_MILLIS = 6000;

    private final WeakReference<Context> mContextRef;
    private AlertDialog mProgressDialog;
    private DialogInterface.OnCancelListener mOnCancelListener;

    private final Runnable mDelayCancel =  () -> {
        if (mProgressDialog != null) {
            mProgressDialog.setOnCancelListener(mOnCancelListener);
            mProgressDialog.setCancelable(true);
            mProgressDialog.setCanceledOnTouchOutside(true);
        }
    };

    private final Handler mHandler = new Handler(Looper.getMainLooper());

    public ProgressDialogHandlerImpl(Context context) {
        mContextRef = new WeakReference<>(context);
    }

    protected AlertDialog createProgressDialog(Context context) {
        AlertDialog alertDialog = new ProgressDialog(context);
        return alertDialog;
    }

    @Override
    public void showProgressDialog(DialogInterface.OnCancelListener listener) {
        mHandler.removeCallbacks(mDelayCancel);
        mOnCancelListener = listener;
        if (mProgressDialog == null) {
            Context context = mContextRef.get();
            if (context != null) {
                mProgressDialog = createProgressDialog(context);
            }
        }

        if (mProgressDialog != null) {
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
            mHandler.postDelayed(mDelayCancel, DELAY_MILLIS);
        }
    }

    @Override
    public void dismissProgressDialog() {
        mHandler.removeCallbacks(mDelayCancel);
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
        mProgressDialog = null;
    }
}
